import React, { useEffect, useState, useRef } from 'react';
import { useModel, history, useSearchParams } from '@umijs/max';
import { Form, Tabs, Space, Button, Switch, Input, Radio, Card } from 'antd';
import SkuTable from './SkuTable.jsx';
import styles from './index.less';
import { Checkbox } from 'antd';

let timer = null;
const skuNameList = ['first_sku_value', 'second_sku_value', 'third_sku_value'];
const sourceMap = [
  'package_name',
  'first_sku_value',
  'second_sku_value',
  'third_sku_value',
];

const SkuTableWrapper = (props) => {
  const { value, onChange } = props;
  const { Spu, Rent, Disabled } = useModel('Goods');
  const [tableColumn, setTableColumn] = useState([]);
  const [prefixColumn, setPrefixColumn] = useState([]);
  const [suffixColumn, setSuffixColumn] = useState([]);
  const [rentPeriodColumn, setRentPeriodColumn] = useState([]);
  const [skuList, setSkuList] = useState([]);
  const [showPer, setShowPer] = useState(false);
  const skuListRef = useRef([]);
  const periodListRef = useRef([]);
  const dataStore = useRef([]);

  const originColumns = [
    {
      title: '是否展示',
      dataIndex: 'show_flag',
      render: (_, record, index) => (
        <Switch
          defaultChecked={Boolean(_)}
          disabled={Disabled}
          onChange={(e) => handleChangeIsHide(e, index)}
        ></Switch>
      ),
    },
    {
      title: '库存',
      dataIndex: 'store',
      editable: true,
      notPrice: true,
      type: 'number',
      inputWidth: 40,
    },
    {
      title: '官方指导价',
      dataIndex: 'selling_price',
      editable: true,
      type: 'number',
    },
    {
      title: '押金',
      dataIndex: 'deposit',
      editable: true,
      type: 'number',
    },
    {
      title: '买断总价',
      dataIndex: 'buyout_price',
      editable: true,
      type: 'number',
    },
  ];
  useEffect(() => {
    reformat();
  }, [Spu, Rent]);

  const reformat = () => {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      formatSkuList();
    }, 100);
  };

  useEffect(() => {
    setTableColumn([
      ...prefixColumn,
      ...originColumns,
      ...rentPeriodColumn,
      ...suffixColumn,
    ]);
  }, [prefixColumn, rentPeriodColumn, suffixColumn]);

  const asyncData = (list, type) => {
    skuListRef.current = list;
    setSkuList(list);
    changeStore(list);
    // console.log('onChange', list)
    onChange(list)
  };

  const changeStore = (list) => {
    list.forEach((i) => {
      const index = dataStore.current.findIndex((it) => it.id === i.id);
      if (index > -1) {
        dataStore.current[index] = i;
      } else {
        dataStore.current.push(i);
      }
    });
  };

  const sumData = (skuFormatedList) => {
    if (skuFormatedList.length && dataStore.current.length) {
      const res = skuFormatedList.map((item) => {
        const skuData =
          dataStore.current.find((i) => {
            if (i.id === item.id || i.formatId === item.formatId) {
              return true;
            } else {
              const formtStr = sourceMap
                .map((t) => item[t])
                .filter((t) => t)
                .join('-');
              const storeStr = sourceMap
                .map((t) => i[t])
                .filter((t) => t)
                .join('-');
              return formtStr === storeStr;
            }
          }) || {};
          
        return {
          ...skuData,
          ...item,
          id: skuData.id || item.formatId,
          show_flag: (skuData.show_flag || skuData.show_flag === 0) ? skuData.show_flag : 1,
        };
      });
      asyncData(res, 'sumData res');
    } else {
      asyncData(
        skuFormatedList.map((i) => ({
          ...i,
          id: i.id || i.formatId,
        })),
        'sumData skuFormatedList',
      );
    }
  };

  useEffect(() => {
    const list = value ? [...value] : [];
    if (
      value &&
      value.length &&
      periodListRef.current &&
      periodListRef.current.length
    ) {
      list.forEach((skuData) => {
        Object.keys(skuData).forEach((keyName) => {
          if (keyName.includes('period_id_')) {
            const id = Number(keyName.replace('period_id_', ''));
            const totalDays = periodListRef.current.find(
              (i) => i.id === id,
            ).total_days;
            const dataIndex = keyName + '-perday';
            const value = skuData[keyName];
            if (value) {
              skuData[dataIndex] = (value / totalDays).toFixed(2) + '元/天';
            } else {
              skuData[dataIndex] = undefined;
            }
          }
        });
      });
    }
    asyncData(list, 'value');
  }, []);

  const handleChangeIsHide = (e, index) => {
    const newList = [...skuListRef.current];
    newList[index].show_flag = e ? 1 : 0;

    asyncData(newList);
    onChange(newList);
  };

  const formatSkuList = () => {
    let newList = [];
    let newColumns = [];
    if (Rent && Rent.length) {
      const tempSpuList = Spu
        ? Spu.map((i) => ({
            ...i,
            values: i.values.filter((it) => it.sku_value),
          }))
        : [];
      const spuList = tempSpuList.filter((i) => i.name && i.values.length);
      let tempList = [];
      if (spuList.length) {
        spuList.forEach((spu, index) => {
          const restSpuList = spuList.slice(index + 1);
          //columns format
          if (restSpuList.length) {
            const restLength = restSpuList.reduce(
              (pv, nv) => pv * nv.values.length,
              1,
            );
            newColumns.push({
              title: spu.name,
              dataIndex: skuNameList[index],
              onCell: (_, idx) => {
                return {
                  rowSpan: idx % restLength === 0 ? restLength : 0,
                };
              },
            });
          } else {
            newColumns.push({
              title: spu.name,
              dataIndex: skuNameList[index],
            });
          }

          tempList = spuList.reduce((list, currentSup, currentIndex) => {
            let processingList = [];
            if (list.length) {
              list.forEach((litem) => {
                currentSup.values.forEach((curSku, curIdx) => {
                  processingList.push({
                    ...litem,
                    [skuNameList[currentIndex]]: curSku.sku_value,
                    skuName: `${litem.skuName}-${curSku.sku_value}`,
                    formatId: `${litem.formatId}-${curSku.id}`,
                  });
                });
              });
            } else {
              currentSup.values.forEach((curSku, curIdx) => {
                processingList.push({
                  [skuNameList[currentIndex]]: curSku.sku_value,
                  skuName: curSku.sku_value,
                  formatId: curSku.id,
                });
              });
            }
            return processingList;
          }, []);
        });
      }

      if (tempList.length) {
        newColumns.unshift({
          title: '套餐',
          dataIndex: 'package_name',
          onCell: (_, index) => {
            return {
              rowSpan: index % tempList.length === 0 ? tempList.length : 0,
            };
          },
        });
        Rent.forEach((rentItem) => {
          tempList.forEach((spu) => {
            const formatId = `${rentItem.id}-${spu.formatId}`;
            newList.push({
              ...spu,
              package_name: rentItem.package_name,
              rent_plan_id: rentItem.id,
              formatId: formatId,
              show_flag: 1,
              // id: spu.id || formatId
            });
          });
        });
      }
      const rentPeriodList = Rent.filter(
        (i) => i.rent_period && i.rent_period.length,
      );
      if (rentPeriodList.length) {
        const periodList = rentPeriodList.reduce((total, curPer) => {
          let temp = curPer.rent_period.reduce((subTotal, subCurPer) => {
            if (
              total.find(
                (i) =>
                  i.id === subCurPer.id &&
                  i.total_days === subCurPer.total_days,
              )
            ) {
              return subTotal;
            } else {
              return [...subTotal, subCurPer];
            }
          }, []);
          return [...total, ...temp];
        }, []);

        periodListRef.current = periodList;

        setRentPeriodColumn(
          periodList.map((per) => ({
            title: per.rent_period,
            dataIndex: `period_id_${per.id}`,
            editable: true,
            type: 'number',
          })),
        );
      }
    }
    setPrefixColumn(newColumns);
    sumData(newList);
  };

  const handleChangeShowPer = (e) => {
    setShowPer(e.target.checked);
    if (e.target.checked) {
      setSuffixColumn(
        periodListRef.current.map((per) => ({
          title: `${per.rent_period}/日租金`,
          dataIndex: `period_id_${per.id}-perday`,
        })),
      );
    } else {
      setSuffixColumn([]);
    }
  };

  const onDataChange = (value, index, key) => {
    const newData = [...skuListRef.current];
    newData[index][key] = value;
    const needCal = key.includes('period_id_');
    if (needCal) {
      const id = Number(key.replace('period_id_', ''));
      const totalDays = periodListRef.current.find(
        (i) => i.id === id,
      ).total_days;
      const dataIndex = key + '-perday';
      if (value) {
        newData[index][dataIndex] = (value / totalDays).toFixed(2) + '元/天';
      } else {
        newData[index][dataIndex] = undefined;
      }
    }
    asyncData(newData);
    onChange(newData);
  };

  // console.log('skuList', skuList)
  return (
    <Card
      title={
        <>
          <Checkbox checked={showPer} onChange={handleChangeShowPer}>
            预览日租金
          </Checkbox>
        </>
      }
      className={styles.sku_card_wrapper}
    >
      <SkuTable
        dataSource={skuList}
        originColumns={tableColumn}
        onDataChange={onDataChange}
      ></SkuTable>
    </Card>
  );
};

export default () => {
  return (
    <Form.Item name="sku" label="规格明细">
      <SkuTableWrapper></SkuTableWrapper>
    </Form.Item>
  );
};
